package com.nanbei.list;

/**
 * @ClassDescription: 循环链表
 * @JdkVersion: 17
 * @Author: BaoShan.li
 * @Created: 2023/11/17 11:12
 */
public class LoopLinkedListSentinel {

    private Node sentinel = new Node(null,9999,null);

    public LoopLinkedListSentinel() {
        sentinel.next = sentinel;
        sentinel.head = sentinel;
    }

    public static class Node{
        Node head;
        int value;
        Node next;

        public Node(Node head, int value, Node next) {
            this.head = head;
            this.value = value;
            this.next = next;
        }
    }

    /**
     * 添加到第一个
     * @param value 待添加值
     */
    public void addFirst(int value) {

        Node node = new Node(this.sentinel, value, sentinel.next);
        sentinel.next.head=node;
        sentinel.next=node;

    }

    /**
     * 添加到最后一个
     * @param value 待添加值
     */
    public void addLast(int value) {
        Node node = new Node(this.sentinel.head, value, sentinel);
        sentinel.head.next=node;
        sentinel.head=node;
    }

    /**
     * 删除第一个
     */
    public void removeFirst() {

        if (sentinel.next==sentinel) {
            throw new IllegalArgumentException("当前链表无节点");
        }
        sentinel.next.next.head=sentinel;
        sentinel.next=sentinel.next.next;
    }

    /**
     * 删除最后一个
     */
    public void removeLast() {
        if (sentinel.next==sentinel) {
            throw new IllegalArgumentException("当前链表无节点");
        }
        sentinel.head.head.next=sentinel;
        sentinel.head = sentinel.head.head;
    }

    /**
     * 根据下标删除节点
     * @param index 待删除值
     */
    public void removeByIndex(int index) {
        Node preNode = findNodeByIndex(index);
        if (preNode == null){
            throw new IllegalArgumentException("数组下标越界");
        }
        preNode.head.next = preNode.next;
        preNode.next.head = preNode.head;

    }

    private Node findNodeByIndex(int index) {
        int i = 0;
        for(Node node = sentinel.next;node != sentinel ;node=node.next,i++){
            if (i == index){
                return node;
            }
        }
        return null;
    }

}
